package newui.page;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.TrainActionHelp;
import com.google.gson.reflect.TypeToken;
import com.humanres.activity.ResMoreActivity;
import com.humanres.activity.ResOtherActivity;
import com.mywork.activity.WorkMeetingActivity;
import com.shwread.android.qysw.activity.JHBActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw.activity.MessageActivity;
import com.shwread.android.qysw.activity.QyFeedBackActivity;
import com.shwread.android.qysw.activity.VoteMainActivity;
import com.shwread.android.qysw.activity.pay.PartyFeePayListActivity;
import com.shwread.android.qysw.activity.task.QuestionnaireListActivity;
import com.shwread.android.qysw10000241.R;
import com.shwread.android.ui.customview.BannerOnClickListener;
import com.shwread.android.ui.customview.QYViewPager;
import com.shwread.android.ui.customview.ViewPagerAdapter;
import com.shwread.android.ui.page.AbstractUIPage;
import com.shwread.android.ui.page.TaskManagementPage;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryMsgsByPositionAction;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.BannerInfo;
import logic.bean.MessageBean;
import logic.bean.MessageInfo;
import logic.constants.DefaultConsts;
import newui.activity.BookListWebActivity;
import newui.adapter.PartyWorldPageAdapter;
import newui.adapter.SmartRecyclerAdapter;
import newui.tools.FullyGridLayoutManager;
import newui.view.AutoVerticalScrollTextView;

/**
 * 党员天地
 */
public class PartyWorldPage extends AbstractUIPage<MainActivity> {

    private static PartyWorldPage instance;

    public static PartyWorldPage getInstance(MainActivity t) {
        if (null == instance) {
            instance = new PartyWorldPage(t);
        } else {
            instance.setActivity(t);
        }
        return instance;
    }

    private PartyWorldPage(MainActivity t) {
        super(t);
    }

    private String[] names = {
            "投票选举",
            "问卷调查",
            "党费缴纳",
            "任务管理",
            "会议签到",
            "请假管理",
            "入党申请",
            "公文传阅",
            "建言献策"};
    private Integer[] ids = {
            R.drawable.img_vote,
            R.drawable.img_questionnaire,
            R.drawable.img_party_play,
            R.drawable.img_task_managerment,
            R.drawable.img_conference_register,
            R.drawable.img_leave_management,
            R.drawable.img_ask_party,
            R.drawable.img_documents,
            R.drawable.img_feedback
    };

    private AutoVerticalScrollTextView vtScrollText;
    private List<String> msgs = null;
    private LinearLayout llMessage;

    private int number = 0;

    private QYViewPager vpPager;
    private ViewGroup vgPoints;
    private ViewPagerAdapter pagerAdapter;
    private List<BannerInfo> banners;


    private Runnable action = new Runnable() {
        @Override
        public void run() {
            if (banners.size() > 0) {
                int currentItem = vpPager.getCurrentItem();
                currentItem++;
                if (currentItem >= pagerAdapter.getCount()) {
                    currentItem = 0;
                }
                vpPager.setCurrentItem(currentItem);
            }

            if (msgs.size() != 0) {
                vtScrollText.setText(msgs.get(number % msgs.size()));
                vtScrollText.next();
                number++;
            }
            handler.postDelayed(this, DefaultConsts.BANNER_CHANGE_TIME);
        }
    };

    private Handler handler = new Handler();

    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.page_party_world, null);
        initView();
        return curMyView;
    }

    private void initView() {
        msgs = new ArrayList<>();
        banners = new ArrayList<>();
        HashMap<Integer, View> views = new HashMap<>();

        vpPager = (QYViewPager) curMyView.findViewById(R.id.my_world_head_pager);
        vgPoints = (ViewGroup) curMyView.findViewById(R.id.my_world_head_points);// banner下面的点
        LinearLayout llVp = (LinearLayout) curMyView.findViewById(R.id.llVp);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) llVp.getLayoutParams();
        lp.height = DefaultConsts.BANNER_DEFAULT_HIGHT;
        lp.width = DefaultConsts.BANNER_DEFAULT_WIDTH;
        llVp.setLayoutParams(lp);

        vtScrollText = (AutoVerticalScrollTextView) curMyView.findViewById(R.id.vtScrollText);
        TextView tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText(bActivity.getResources().getString(R.string.main_tab_str3));
        ImageView ivPerson = (ImageView) curMyView.findViewById(R.id.common_header_persion);
        llMessage = (LinearLayout) curMyView.findViewById(R.id.llMessage);
        ivPerson.setVisibility(View.VISIBLE);
        ivPerson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bActivity.goPersonalActivity();
            }
        });
        RecyclerView recyclerView = (RecyclerView) curMyView.findViewById(R.id.recyclerView);
        FullyGridLayoutManager gridLayoutManager = new FullyGridLayoutManager(bActivity, 4);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(gridLayoutManager);
        PartyWorldPageAdapter adapter = new PartyWorldPageAdapter(names, ids);
        SmartRecyclerAdapter smartRecyclerAdapter = new SmartRecyclerAdapter(adapter);
        adapter.setOnRecyclerViewItemClickListener(new PartyWorldPageAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, String tag) {
                switch (tag) {
                    case "投票选举":
                        intent2Acticity(VoteMainActivity.class, "投票选举");
                        break;
                    case "问卷调查":
                        intent2Acticity(QuestionnaireListActivity.class);
                        break;
                    case "党费缴纳":
                        intent2Acticity(PartyFeePayListActivity.class);
                        break;
                    case "任务管理":
                        bActivity.changePage(TaskManagementPage.getInstance(bActivity), DEFAULT_STATUS);
                        break;
                    case "会议签到":
                        intent2Acticity(WorkMeetingActivity.class, "会议签到");
                        break;
                    case "请假管理":
                        intent2Acticity(ResMoreActivity.class, "请假管理");
                        break;
                    case "入党申请":
                        intent2Acticity(JHBActivity.class, "入党申请");
                        break;
                    case "公文传阅":
                        intent2Acticity(ResOtherActivity.class, "公文传阅");
                        break;
                    case "建言献策":
                        intent2Acticity(QyFeedBackActivity.class, "建言献策");
                        break;
                    default:
                        bActivity.changePage(LoginViewPage.getInstance(bActivity), DEFAULT_STATUS);
                        break;
                }
            }
        });
        recyclerView.setAdapter(smartRecyclerAdapter);
        vtScrollText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bActivity.startActivity(new Intent(bActivity, MessageActivity.class));
            }
        });
        vpPager.addOnPageChangeListener(new PagerChangeListener());
        pagerAdapter = new ViewPagerAdapter(bActivity, views, new BannerClick());
        vpPager.setAdapter(pagerAdapter);
        TrainActionHelp.qryBannerListByPosition(bActivity, 7, new QryBannerListByPositionHandler());
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        new QryMsgsByPositionAction(bActivity, DefaultConsts.TYPE_POSITION_MESSAGECENTER, DefaultConsts.TYPE_WRITESOURCE_ALL, 1, 2000, new GetMsgAction()).start();
        handler.removeCallbacks(action);
        handler.postDelayed(action, DefaultConsts.BANNER_CHANGE_TIME);//每3s执行一次runnable.
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {

    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    public static void destroy() {
        if (instance != null) {
            instance.dispose();
            instance = null;
        }
    }

    @Override
    public void dispose() {
        super.dispose();
    }

    private class GetMsgAction extends BaseAction {

        @Override
        protected void onError() {
            Log.e("sss", "消息加载失败");
            super.onError();
        }

        @Override
        public void OK(Object obj) {
            Log.e("sss", "消息加载成功");
            final MessageBean msg = (MessageBean) obj;
            List<MessageInfo> messages = msg.getColumns();
            if (messages == null || messages.size() == 0) {
                bActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        llMessage.setVisibility(View.GONE);
                    }
                });
            } else {
                for (int i = 0; i < messages.size(); i++) {
                    msgs.add(messages.get(i).getTitle());
                }
                bActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        vtScrollText.setText(msgs.get(0));
                    }
                });
            }
        }
    }

    /**
     * Banner点击事件
     */
    private class BannerClick implements BannerOnClickListener {
        @Override
        public void click(BannerInfo info) {
            clickBanner(info);
        }
    }

    /**
     * Banner的滚动事件
     */
    private class PagerChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int i) {
            int pageIndex = i;
            if (i == 0) {
                // 当视图在第一个时，将页面号设置为图片的最后一张。
                pageIndex = banners.size() - 2;
            } else if (i == banners.size() - 1) {
                // 当视图在最后一个是,将页面号设置为图片的第一张。
                pageIndex = 1;
            }
            if (i != pageIndex) {
                vpPager.setCurrentItem(pageIndex, false);
            }
            setViewPoint();
        }
    }

    private void initBannerView() {
        if (banners.size() == 0) {
            return;
        }
        vgPoints.removeAllViews();
        for (int i = 0; i < banners.size() - 2; i++) {
            View view = bActivity.getLayoutInflater().inflate(R.layout.banner_grid_item, null);
            vgPoints.addView(view);
        }
        vpPager.setCurrentItem(1);
        setViewPoint();
        pagerAdapter.notifyDataSetChanged();
    }

    private void setViewPoint() {
        for (int i = 0; i < vgPoints.getChildCount(); i++) {
            View view = vgPoints.getChildAt(i);
            ImageView img = (ImageView) view.findViewById(R.id.banner_grid_item_image);

            if (i == vpPager.getCurrentItem() - 1) {
                img.setBackgroundResource(R.drawable.banner_grid_cur);
            } else {
                img.setBackgroundResource(R.drawable.banner_grid);
            }
        }
    }

    private void clickBanner(BannerInfo info) {
        switch (info.getType()) {
            case BannerInfo.TYPE_BANNER:
                break;
            case BannerInfo.TYPE_BOOKS:
                break;
            case BannerInfo.TYPE_BOOKSURL:
                bActivity.goBookDetailActivity(info.getBooks());
                break;
            case BannerInfo.TYPE_URL:
            case BannerInfo.TYPE_INFORMATION:
                Intent webIntent = new Intent(bActivity, BookListWebActivity.class);
                webIntent.putExtra(DefaultConsts.title_s, info.getBannerName());
                webIntent.putExtra(DefaultConsts.req_url_s, info.getContent());
                webIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                bActivity.startActivity(webIntent);
                break;
        }
    }

    private class QryBannerListByPositionHandler extends ObjectHttpResponseHandler<List<BannerInfo>> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, List<BannerInfo> infoList, String responseString) {
            banners.clear();
            if (infoList.size() <= 1) {
                banners = infoList;
            } else {
                banners.add(infoList.get(infoList.size() - 1));
                banners.addAll(infoList);
                banners.add(infoList.get(0));
            }
            if (banners.size() > 0) {
                pagerAdapter.setData(banners);
                initBannerView();
            }
        }

        @Override
        public Type getType() {
            return new TypeToken<List<BannerInfo>>() {
            }.getType();
        }
    }
}